<template>
  <div class="container">
    <div class="app-container">
      <!-- 树形结构
       data 提供数据
       props 默认属性配置 -> 默认字段 children / label  可以进行自定义
       default-expand-all	是否默认展开节点
      -->
      <el-tree :data="depts" default-expand-all :props="defaultProps" :expand-on-click-node="false">
        <!-- 自定义结构 默认插槽 #default="{node, data}" data -->
        <template #default="{ data }">
          <el-row style="width: 100%;" type="flex" justify="space-between">
            <el-col>
              <span>{{ data.name }}</span>
            </el-col>
            <el-col :span="4">
              <span class="manager">{{ data.managerName }}</span>
              <!-- 下拉操作菜单 -->
              <el-dropdown @command="operateDept($event,data.id)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>

        </template>

      </el-tree>
    </div>
    <!-- 添加/编辑部门 导入子组件-->
    <addDept ref="addDept" :current-id="currentId" :show-dialog.sync="showDialog" @updateDepartment="getDepartment" />
    <!-- <addDept
      :show-dialog="showDialog"
      @update:showDialog="showDialog = $event"
    /> -->
  </div>
</template>
<script>
import { delDepartment, getDepartment } from '@/api/department'
import { translateListToTreeData } from '@/utils'
import AddDept from './componment/add-dept.vue'

export default {
  name: 'Department',
  // 导入组件
  components: {
    AddDept
  },
  data() {
    return {
      depts: [],
      defaultProps: {
        label: 'name'
      },
      showDialog: false,
      currentId: null // 点击的部门id
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    async getDepartment() {
      const res = await getDepartment()
      this.depts = translateListToTreeData(res, 0)
    },
    operateDept(type, id) {
      // console.log('你的操作是', type)
      if (type === 'add') {
        this.showDialog = true
        // id进行赋值
        this.currentId = id
      } else if (type === 'edit') {
        // 编辑部门
        this.showDialog = true
        this.currentId = id
        this.$nextTick(() => {
          this.$refs.addDept.getDepartmentDetail()
        })
      } else {
        // 删除部门
        this.$confirm('您确认要删除该部门吗').then(async() => {
          await delDepartment(id)
          // 提示消息
          this.$message.success('删除部门成功')
          this.getDepartment()
        })
      }
    }
  }
}
</script>
<style>
.manager{
  display: inline-block;
  width: 80px;
}
.app-container {
  padding: 30px 40px;
  font-size: 14px;
}
</style>
